<?php

namespace app\admin\controller\customer;

use app\admin\model\customer\package\User;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 客户服务内容
 *
 * @icon fa fa-circle-o
 */
class Service extends Backend
{

    /**
     * Service模型对象
     * @var \app\admin\model\customer\Service
     */
    protected $model = null;
    public $relationSearch = true;
    public $searchFields = 'package.package_id';

//    protected $dataLimit = 'auth'; //默认基类中为false，表示不启用，可额外使用auth和personal两个值
//    protected $dataLimitField = 'admin_id';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\customer\Service;

    }

    public function index($ids = '')
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {

            if (!$this->auth->isSuperAdmin()) {
                $admin = $this->auth->getUserInfo();
                $admin_id = $this->auth->id;

                if ($admin['identity'] == 0) {
                    $package_ids = (new \app\admin\model\customer\Package())->where(['admin_id' => $admin_id])->column('package_id');
                } else {
                    $package_ids = (new User())->where(['admin_id' => $admin_id])->column('package_id');
                }

                $this->assignconfig('package_ids', $package_ids);
            }
            $this->assignconfig('customer_id', $ids);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['customer', 'package'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $total = [
            'id' => '合计',
            'customer_id' => 152,
            'package_id' => 67,
            'service_id' => 15,
            'service_name' => '-',
            'corporate_type' => 0,
            'standard_price' => $this->model
                ->with(['package'])
                ->where($where)->sum('standard_price'),
            'cost_type' => 1,
            'cost_price' => $this->model
                ->with(['package'])
                ->where($where)->sum('cost_price'),
            'deal_price' => $this->model
                ->with(['package'])
                ->where($where)->sum('deal_price'),
            'collection_price' => $this->model
                ->with(['package'])
                ->where($where)->sum('collection_price'),
            'balance_price' => $this->model
                ->with(['package'])
                ->where($where)->sum('balance_price'),
            'account_commission_type' => 2,
            'account_commission' => '30.00',
            'sales_commission_type' => 0,
            'sales_commission' => '525.00',
            'outworker_commission_type' => 0,
            'outworker_commission' => '0.00',
            'ledger_expenses' => '0.00',
            'create_time' => 0,
            'month' => '-',
            'start_time' => 0,
            'end_time' => 0,
            'customer' => [
                'id' => 152,
                'admin_id' => 1,
                'customer_identity' => 0,
                'full_name' => '-',
                'idnumber' => '-',
                'corporate_name' => '-',
                'signatory' => 'cs',
                'customer_type' => 0,
                'mobile' => '18570274710',
                'corporate_type' => 0,
                'region' => '安徽省/芜湖市/鸠江区',
                'create_time' => 1711673893,
                'create_time_text' => '2024-03-29 08:58:13',
                'admin_info' => '-',
                'total_amount' => 3600,
                'audit_status' => [
                    'wtj' => 1,
                    'shz' => 0,
                    'shtg' => 0,
                    'shbtg' => 0,
                ],
            ],
            'create_time_text' => '-',
            'start_time_text' => '-',
            'end_time_text' => '-',
            'distance_days' => '-',
        ];
        $array = $list->items();
        $array[] = $total;
        $result = ['total' => $list->total(), 'rows' => $array];
        return json($result);
    }

    public function disposable()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            if (!$this->auth->isSuperAdmin()) {
                $admin = $this->auth->id;
                $package_ids = (new User())->where(['admin_id' => $admin])->column('package_id');
                $this->assignconfig('package_ids', $package_ids);
            }
            return $this->view->fetch('customer/service/index');
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 数据汇总
     */
    public function datasummary()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            if (!$this->auth->isSuperAdmin()) {
                $admin = $this->auth->id;
                $package_ids = (new User())->where(['admin_id' => $admin])->column('package_id');
                $this->assignconfig('package_ids', $package_ids);
            }
            return $this->view->fetch('customer/service/index');
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    public function saveCommission($id, $field, $commission)
    {
        $cs = $this->model::get($id);
        if (!$cs) {
            $this->error('未找到记录！');
        }

        $data = [];
        $data[$field] = $commission;
        if (!$cs->allowField(true)->save($data)) {
            $this->error('操作失败');
        }
        $this->success();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if (!empty($params['start_time'])) {
            $params['start_time'] = strtotime($params['start_time']);
        }

        if (!empty($params['end_time'])) {
            $params['end_time'] = strtotime($params['end_time']);
        }

        if (!empty($params['create_time'])) {
            $params['create_time'] = strtotime($params['create_time']);
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
